package com.xqboss.apps.service.order.pay.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeCloseModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.WebUtils;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.xqboss.apps.domain.order.PayAccount;
import com.xqboss.apps.domain.order.PayApply;
import com.xqboss.apps.dto.order.SignPayDto;
import com.xqboss.apps.dto.order.TradeResultDto;
import com.xqboss.apps.enums.order.PayAccountTypeEnum;
import com.xqboss.apps.enums.user.PayTypeEnum;
import com.xqboss.apps.service.order.PayAccountService;
import com.xqboss.apps.service.order.pay.PayExecutor;
import com.xqboss.common.config.XQBossConfig;
import com.xqboss.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Trent
 * @date 2023/8/23
 */
@Slf4j
@Component(value = PayTypeEnum.Code.Alipay_APP)
public class AliPayAppExecutor extends BaseAliPay {

    @Override
    public SignPayDto signPay(PayApply info) {
        try {
            if(XQBossConfig.isTestEnable()){
                WebUtils.setNeedCheckServerTrusted(false);
            }
            PayAccount payAccount = payAccountService.getCurrentPayAccount(PayAccountTypeEnum.ALIPAY);
            if(payAccount == null){
                throw new ServiceException("支付通道维护中,请选择其他支付方式");
            }
            AlipayClient alipayClient = new DefaultAlipayClient(gateway, payAccount.getAppId(), payAccount.getPrivateKey(), format, charset, payAccount.getPublicKey(), signType);
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            //异步接收地址，仅支持http/https，公网可访问
            request.setNotifyUrl(notifyUrl + payAccount.getId());
            //同步跳转地址，仅支持http/https
//            request.setReturnUrl("");
            AlipayTradeAppPayModel bizModel = new AlipayTradeAppPayModel();
            bizModel.setOutTradeNo(String.valueOf(info.getId()));
            bizModel.setTotalAmount(info.getOrderAmount().toPlainString());
            bizModel.setSubject("加油蛙-" + info.getSubject());
            // 订单支付超时时间
            bizModel.setTimeExpire(info.getExpireTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            request.setBizModel(bizModel);
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                SignPayDto dto = new SignPayDto();
                dto.setOutTradeNo(response.getTradeNo());
                dto.setPayInfo(response.getBody());
                dto.setPayAccountId(payAccount.getId());
                return dto;
            } else {
                log.error("生成支付失败:{} - {}", info.getId(), JSONObject.toJSONString(response));
                throw new ServiceException("支付失败，请重试");
            }
        } catch (ServiceException e){
            throw e;
        } catch (Exception e) {
            log.error("生成支付异常", e);
            throw new ServiceException("支付失败，请重试");
        }
    }

}
